const app = getApp();
let liveroom = require('../../utils/liveroom.js');
import { getUserInfo } from '../../../common/utils/ws/wsxcx-opendata-sdk';
const device = wx.getSystemInfoSync();

// 没使用到
let errorCode = [
    { '-9001': '创建房间失败' },
    { '-9002': '获取推流地址失败' },
    { '-9003': '进入房间失败' },
    { '-9004': '请求连麦失败' },
    { '-9005': '发送消息失败'},
    { '-9006': '房间已经解散了'},
];

let _this = null;
let gListMenus = [{ name: '静音' }, { name: '美颜' }, { name: '相机' }, { name: '连麦' }];
let memberInterval = null;
Component({
    properties: {
        role: { type: String, value: 'audience' },
        roomid: {
      type: String,
      value: '',
      observer: function(newVal, oldVal) {
                this.data.roomID = newVal;
      },
        },
        createType:{
          type: String,
      value: '',
        },
        isShowVoice:{
          type: Boolean,
          value: false,
        },
    roomName: { type: String, value: 'undefined' },
        debug: { type: Boolean, value: false },
        template: { type: String, value: '1v3' },
        beauty: { type: Number, value: 5 },
        muted: {type: Boolean, value: false},
    pureAudio: { type: Boolean, value: false },
    },

    data: {
    anchorAvatar: '',
        isCaster: true,
        userName: '',
        userID: '',
        roomID: '',
        pusherContext: null,
        playerContext: null,
        linkedPlayerContext: null,
        unload: 1,
        isInRoom: 0,
        unfold: false,
        mainPusherInfo: {
            url: '',
            aspect: '3:4',
            minBitrate: 0,
            maxBitrate: 0,
            puserID: '',
        },
        audience: {
            url: null,
            mixUrl: null,
            accelerateUrl: null,
            pusherName: '',
            pusherID: '',
            isLinked: false,
            aspect: '3:4',
            loading: false,
      objectFit: false,
        },
        linkPusherInfo: {
            url: '',
            loading: true,
            debug: true,
        },
        members: [],
        audiences: [],
        audienceCount: 0,
        visualPlayers: [],
        requestLinking: false,
    mode: 'SD',
    showComment: false,
    comment: [],
    casterComment: [],
    tip: '',
    tipAnimation: {},
    },
  mealInterval: null,
  heartInterval: null,
  trtcAccountRoomCreated: false,
  accountAuthChecked: false,
  isAccountAuth: false,

    methods: {
    getUserInfo1() {
      getUserInfo().then(userInfo => {
         const anchorAvatar = userInfo.avatarUrl;
        this.setData({
          anchorAvatar: anchorAvatar,
        });
        console.log('userInfo---------', userInfo);
        console.log('anchor---------', this.anchor);
        console.log('anchorAvatar---------', this.anchorAvatar);
      }).catch(res => {
        // app.util.navigateTo('/cm_lvb/pages/auth/auth');
      });
    },
    showComment() {
      this.setData({
        inputMsg: '',
        showComment: true,
      });
    },
    hideComment() {
      this.setData({
        inputMsg: '',
        showComment: false,
      });
    },
    bindInputMsg(e) {
      this.setData({
        inputMsg: e.detail.value,
      });
    },
    sendComment() {
      if (this.data.inputMsg) {
        this.sendTextMsg(this.data.inputMsg);
      }
      this.setData({
        inputMsg: '',
        showComment: false,
      });
    },
    toLiveRoom() {
      const pages = getCurrentPages();
      if (pages && pages.length > 1) {
        wx.navigateBack();
      } else {
        app.util.navigateTo('/cm_trtc_1/pages/live-phone/roomlist/roomlist');
      }
    },
    checkDebug() {
      app.util.request({
        url: 'entry/wxapp/index',
        data: {
          op: 'checkSwitch',
        },
        module: 'cm_trtc',
        success: res => {
          if (res.data && res.data.errno == 0) {
            const data = res.data.data;
            if (data) {
              this.setData({ debug: data.is_debug == 1 });
            }
          }
        },
      });
    },
        toggleDebug(){
      let self = this;
      self.setData(
        {
          debug: !self.data.debug,
        },
        () => {
                console.log('>> Debug: ', self.data.debug);
        },
      );
        },
        toggleBeauty(){
      let self = this;
      let bty = self.data.beauty == 5 ? 0 : 5;
      if (!this.data.pureAudio) {
      self.setData(
        {
          beauty: bty,
        },
        () => {
          console.log(bty > 0 ? '开启美颜' : '关闭美颜');
        },
      );
      } else {
        wx.showToast({
          title: '纯音频模式无法开启美颜 ',
          icon: 'none',
        });
            self.setData({
          beauty: 0,
        });
      }
        },
        toggleMuted(){
      let self = this;
      self.setData(
        {
          muted: !self.data.muted,
        },
        () => {
          console.log(self.data.muted ? '静音' : '非静音');
        },
      );
        },
        sendTextMsg(text) {
      let self = this;
            if (text.startsWith('>')){
                switch(text){
                    case '>debug': {
                        self.toggleDebug();
                        return;
                    }
                }
            }
            liveroom.sendRoomTextMsg({
                data:{msg: text},
        success: () => {},
                fail: (e) => {
          console.log('发送消息失败: ', e);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9005,
            detail: `发送消息失败`,
          });
        },
            });
        },
        switchCamera(){
      let self = this;
      console.log('切换摄像头: ', self.data.pusherContext);
            self.data.pusherContext && self.data.pusherContext.switchCamera({});
        },
        respondJoinReq(agree, audience) {
      console.info(`respondJoinReq(agree:${agree}, audience:${audience}) called`);
            if (agree) {
        this.checkAuth().then(() => {
          if (this.isAccountAuth) {
            this.checkMeal('trtc').then(() => {
              const memberCount = this.data.members.filter(v => v.userID).length;
              if (!this.trtcAccountRoomCreated) {
                this.trtcAccountRoomCreated = true;
                return this.createAccountRoom(this.data.roomID, 2);
              } else if (memberCount === 0) {
                return this.joinAccountRoom(2);
              }
            });
          }
        }).then(() => {
                liveroom.acceptJoinPusher({
          data: audience,
                });
        });
            } else {
                liveroom.rejectJoinPusher({
          data: audience,
                });
            }
        },

        setupLiveRoomListener() {
      let self = this;
            liveroom.setListener({
                onRoomClose: self.onRoomClose,
                onRecvRoomTextMsg: self.onRecvRoomTextMsg,
                onSketchpadData: self.onSketchpadData,
                onKickOut: self.onKickOut,
                onRecvJoinPusherRequest: self.onRecvJoinPusherRequest,
                onPusherQuit: self.onPusherQuit,
                onPusherJoin: self.onPusherJoin,
        onPushersChange: self.onPushersChange,
            });
        },

        start() {
      console.info('start() called');
      let self = this;
      if (self.data.isCaster == false) {
        // 观众
                self.enter();
      } else {
        // 主播
                //请求CGI:get_push_url，异步获取到推流地址pushUrl
                liveroom.getPushURL({
                    success: function (ret) {
                        console.log('getPushURL 成功，', ret);
                        self.data.mainPusherInfo.url = ret.pushURL;
            const mode = self.data.pureAudio ? 'RTC' : 'SD';
            console.log('设置推流模式为: ' + mode);
            self.setData(
              {
                            mainPusherInfo: self.data.mainPusherInfo,
                mode,
              },
              function() {
                            self.setupLiveRoomListener();
                            self.data.pusherContext = wx.createLivePusherContext('pusher');
                            console.log('创建 pusherContext：', self.data.pusherContext);
                            //开始推流
                self.data.pusherContext.start({
                  success: function() {
                    let context = wx.createCanvasContext('caster-comment', self);
                    self.ctx = context;
                  },
                        });
              },
            );
          },
          fail: function (ret) {
            console.log('获取推流地址失败: ', ret);
            self.triggerEvent('RoomEvent', {
              tag: 'error',
              code: -9002,
              detail: `获取推流地址失败`,
            });
          },
        });
      }
                        if (memberInterval) {
                          clearInterval(memberInterval);
                        }
                        memberInterval = setInterval(() => {
                          liveroom.getAudiences({
                            success: function (res) {
                              if (res.data && res.data.code === 0) {
                                const audiences = res.data.audiences;
                                const audienceCount = res.data.audienceCount;
                    const enterAudiences = audiences.filter(
                      (v) => self.data.audiences.findIndex((a) => a.userID === v.userID) === -1,
                    );
                    const leaveAudiences = self.data.audiences.filter(
                      (v) => audiences.findIndex((a) => a.userID === v.userID) === -1,
                    );
                                if (enterAudiences.length > 0 || leaveAudiences.length > 0) {
                                  self.triggerEvent('RoomEvent', {
                                    tag: 'audienceChange',
                                    code: 0,
                                    detail: { enterAudiences, leaveAudiences },
                                  });
                                  self.setData({
                                    audiences,
                                    audienceCount,
                                  });
                      for (let i = 0; i < enterAudiences.length; i++) {
                        const audience = enterAudiences[i];
                        const userInfo = JSON.parse(audience.userInfo);
                  self.tips.push(`欢迎 ${userInfo.userName} 进入直播间`);
                  self.showTip();
                      }
                      for (let i = 0; i < leaveAudiences.length; i++) {
                        const audience = leaveAudiences[i];
                        const userInfo = JSON.parse(audience.userInfo);
                        self.onRecvRoomTextMsg({
                          message: `${userInfo.userName}离开房间`,
                        });
                      }
                                }
                              }
                            },
                          });
                        }, 5000);
                    },
        stop() {
            console.log('stop() called');
      let self = this;
            console.log('stop pusherContext：', self.data.pusherContext, self.data.playerContext);
            self.data.pusherContext && self.data.pusherContext.stop();
            self.data.playerContext && self.data.playerContext.stop();
      let players = self.data.members;
      players &&
        players.forEach((p) => {
          p.context && p.context.stop();
        });
            // 重置信息
            self.setData({
                unload: 1,
                members: [{}],
                visualPlayer: [],
                pusherContext: null,
                playerContext: null,
                linkedPlayerContext: null,
            });
            self.exit();
            liveroom.setListener({});
        },
        pause() {
            console.log('pause() called');
      let self = this;
            self.data.pusherContext && self.data.pusherContext.pause();
            self.data.playerContext && self.data.playerContext.pause();
        },
        resume() {
            console.log('resume() called');
      let self = this;
            self.data.pusherContext && self.data.pusherContext.resume();
            self.data.playerContext && self.data.playerContext.resume();
        },

        onPusherJoin(ret) {
      console.log('==> onPusherJion() called: ', ret);
      let self = _this;
      let temp = self.data.members.filter((e) => e.userID);
      let pushers = ret.pushers;
            //去掉自己
      let index = pushers.map((p) => p.userID).indexOf(self.data.userID);
            if (index != -1) pushers.splice(index, 1);
            //去掉主播
      index = pushers.map((p) => p.userID).indexOf(self.data.audience.pusherID);
            if (index != -1) pushers.splice(index, 1);

      console.log(`%c===> ${pushers.length} 人加入Link`, 'color: red');
      pushers = pushers.map((p) => {
                return {
                    userID: p.userID,
                    userName: p.userName,
                    accelerateURL: p.accelerateURL,
          context: null,
        };
            });

            temp = temp.concat(pushers);
            switch(self.data.template){
                case '1v1': {
                    if (temp.length > 1) {
                        temp.splice(1, temp.length -1);
                    }else if (temp.length < 1) {
                        temp.push({});
                    }
                    break;
                }
                case 'vertical1v3':
                case '1v3': {
                    if (temp.length > 3){
                        temp.splice(3, temp.length - 3);
                    }else {
            let left = 3 - temp.length - (!self.data.isCaster && self.data.linkPusherInfo.url ? 1 : 0);
            for (let i = 0; i < left; i++) {
                            temp.push({});
                        }
                    }
                    break;
                }
            }

            console.log('设置推流模式为:RTC');
      self.setData(
        {
                members: temp,
          mode: 'RTC',
        },
        function() {
          temp.forEach((p) => {
                    if (p.context) return;
            if (p.userID) p.context = wx.createLivePlayerContext(p.userID, self);
          });
          console.log('data.members: ', self.data.members);
        },
      );
        },

        onPusherQuit(ret) {
      console.log('===> onPusherQuit() called: ', ret);
      let self = _this;
      let temp = [];
      let pushers = ret.pushers;
      let members = self.data.members;
      for (let p of pushers) {
                for (var i in members) {
                    if (p.userID == members[i].userID) {
                        members[i].context && members[i].context.stop();
                        members.splice(i, 1);
                        members.push({});
                        break;
                    }
                }
            }

      let mode = 'SD';
            for (var i=0; i<members.length; ++i) {
                if (members[i].userID) {
                    mode = 'RTC';
                }
            }
            console.log('设置推流模式为:', mode);

      const memberCount = self.data.members.filter(v => v.userID).length;
      if (self.isAccountAuth && self.data.isCaster && memberCount === 0) {
        self.leaveAccountRoom(2);
      }

      self.setData(
        {
                members: members,
          mode: mode,
        },
        () => {
          console.log('members after onPusherQuit: ', self.data.members);
        },
      );
        },
        onRecvJoinPusherRequest(pusher) {
      let self = _this;
      console.log('onRecvJoinPusherRequest() called, pusher = ', JSON.stringify(pusher));
            self.triggerEvent('RoomEvent', {
                tag: 'joinPusher',
                code: 0,
        detail: pusher,
      });
        },
        onKickOut() {
      console.log('onKickOut() called');
        },
        enter() {
      let self = this;
            console.log('enter room width roomid: ', self.data.roomID);
            liveroom.setListener({
                onRoomClose: self.onRoomClose,
                onRecvRoomTextMsg: self.onRecvRoomTextMsg,
                onSketchpadData: self.onSketchpadData,
                onPusherQuit: self.onLinkPusherQuit,
                onPusherJoin: self.onPusherJoin,
                onKickOut: self.onLinkKickOut,
        onPushersChange: self.onPushersChange,
            });
            liveroom.enterRoom({
                data: {
          roomID: self.data.roomID,
                },
                success: function (ret) {
          console.info('enterRoom 成功: ', ret);
                    self.data.audience.url = ret.mixedPlayURL;
                    self.data.audience.mixUrl = ret.mixedPlayURL;
                    self.data.mainPusherInfo.puserID = ret.roomCreator;
                    if (ret.pushers && ret.pushers.length > 0) {
                        self.data.audience.pusherName = ret.pushers[0].userName;
                        self.data.audience.pusherID = ret.pushers[0].userID;
                        self.data.audience.accelerateUrl = ret.pushers[0].accelerateURL;
                    } else {
                        console.error('缺少加速流');
                    }
                    //{ "cmd":"C2CCustomMsg", "data":{ userName: "xxx", userAvatar:"xxx", "roomID":"XXX", "cmd":"xx", msg:"xx" } }
          // liveroom.sendC2CCustomMsg({ cmd: 'sketchpad', msg: '{"type":"request", "action":"currentPPT"}' });
          self
            .playMixedUrl()
            .then(() => {
              let context = wx.createCanvasContext('audience-comment', self);
              self.ctx = context;
                        console.log('playMixedUrl done');
            })
            .catch((e) => {
              console.log('playMixedUrl Error: ', e);
                    });
          self.checkAuth().then(() => {
            if (self.isAccountAuth) {
              self.joinAccountRoom(1);
              self.heartInterval = setInterval(() => {
                self.accountHeart();
              }, 60 * 1000);
            }
          });
                },
                fail: function (ret) {
          console.error('enterRoom 失败: ', ret);
                    if (!self.data.unload) {
                        self.data.playerContex && self.data.playerContext.stop();
                        self.triggerEvent('RoomEvent', {
                            tag: 'error',
                            code: -9003,
              detail: 'enterRoom 失败',
            });
                }
        },
            });
        },

        create() {
      console.log('create() called');
      let self = this;
            liveroom.createRoom({
                data: {
          roomInfo: JSON.stringify({ roomName: self.data.roomName, pureAudio: self.data.pureAudio }),
          pushURL: self.data.mainPusherInfo.url,
                },
                success: function (ret) {
                    console.log('创建房间成功, ret = ', ret);
                    self.setData({
            roomID: ret.roomID,
          });
                    if(self.data.createType==='create'){
            self.checkAuth().then(() => {
              if (self.isAccountAuth) {
                return self.createAccountRoom(ret.roomID, 1);
              }
            }).then(() => {
                      self._setRooomPassWord(self.data.roomID,app.globalData.roomPassWord,app.globalData.connectStatus);
              if (self.isAccountAuth) {
                self.mealInterval = setInterval(() => {
                  self.checkMeal();
                }, 10 * 60 * 1000);
                self.heartInterval = setInterval(() => {
                  self.accountHeart();
                }, 60 * 1000);
              }
            }).catch(() => {
              self.stop();
            });
                    }
                    self.triggerEvent('RoomEvent', {
                        tag: 'created',
                        code: 0,
            detail: '创建房间成功',
          });
                },
                fail: function (ret) {
          console.error('创建房间失败', ret);
                    if (!self.data.unload) {
                        self.data.pusherContext.stop();
                    }
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9001,
            detail: '创建房间失败',
          });
        },
            });
        },

        exit: function () {
      console.log('exit() called');
            liveroom.exitRoom({});
      if (this.isAccountAuth) {
        this.leaveAccountRoom(1);
        if (this.data.createType === 'create') {
          this.destroyAccountRoom(1);
        }
        if (this.trtcAccountRoomCreated) {
          this.destroyAccountRoom(2);
        }
        if (this.mealInterval) {
          clearInterval(this.mealInterval);
        }
        if (this.heartInterval) {
          clearInterval(this.heartInterval);
        }
      }
    },

    checkAuth() {
      return new Promise((resolve, reject) => {
        if (this.accountAuthChecked) {
          return resolve();
        }
        app.util.request({
          url: 'wxapp/accounting/is_auth',
          module: 'cm_trtc',
          success: res => {
            if (res.data.errno == 0) {
              this.accountAuthChecked = true;
              this.isAccountAuth = res.data.data && res.data.data.is_auth == 1;
              return resolve();
            }
          },
        });
      });
    },

    createAccountRoom(roomid, type) {
      return new Promise((resolve, reject) => {
        app.util.request({
          url: 'wxapp/accounting/createRoom',
          data: {
            roomid,
            type,
          },
          module: 'cm_trtc',
          success: res => {
            if (res.data.errno == 0) {
              resolve();
            } else {
              wx.showModal({
                title: '提示',
                content: res.data.message,
                showCancel: false,
              });
              reject(res.data.message);
            }
          },
        });
      });
    },

    destroyAccountRoom(type) {
      app.util.request({
        url: 'wxapp/accounting/destroyRoom',
        data: {
          roomid: this.data.roomID,
          type,
        },
        module: 'cm_trtc',
        success: res => {

        },
      });
    },
    joinAccountRoom(type) {
      app.util.request({
        url: 'wxapp/accounting/joinRoom',
        data: {
          roomid: this.data.roomID,
          type,
        },
        module: 'cm_trtc',
        success: res => {

        },
      });
    },
    leaveAccountRoom(type) {
      app.util.request({
        url: 'wxapp/accounting/leaveRoom',
        data: {
          roomid: this.data.roomID,
          type,
        },
        module: 'cm_trtc',
        success: res => {

        },
      });
    },
    checkMeal(type) {
      const data = {};
      if (type) {
        data.meal_type = type;
      }
      return new Promise((resolve, reject) => {
        app.util.request({
          url: 'wxapp/accounting/checkMeal',
          data,
          module: 'cm_trtc',
          success: res => {
            if (res.data && res.data.errno == 1) {
              wx.showModal({
                title: '提示',
                content: '音视频服务套餐时长不足，请联系管理员充值',
                showCancel: false,
              });
            }
            resolve();
          },
          fail: res => {
            if (res.data && res.data.errno == 2) {
              wx.showModal({
                title: '提示',
                content: '音视频服务套餐时长不足，需要充值后才能继续使用',
                showCancel: false,
                success: () => {
                  if (type) {
                    reject(res);
                  } else {
                    wx.navigateBack({ delta: 1 });
                  }
                },
              });
            }
          },
        });
      });
    },
    accountHeart() {
      app.util.request({
        url: 'wxapp/accounting/heart',
        data: {
          roomid: this.data.roomID,
        },
        module: 'cm_trtc',
        success: res => {

        },
      });
    },
        onPlay(ret) {
      let self = this;
            console.error('拉流情况：', ret.detail.code);
            switch (ret.detail.code) {
                case -2301: {
                    // 多次拉流失败
          console.error('多次拉流失败');
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: ret.detail.code,
            detail: '多次拉流失败',
                    });
                    break;
        }
            }
        },

        linkJionPusher() {
      console.log('linkJionPusher() called');
      let self = this;
            liveroom.joinPusher({
                data: {
                    pushURL: self.data.linkPusherInfo.url,
          roomID: self.data.roomID,
                },
                success: function () {
          console.log('连麦成功完成');
          self.checkAuth().then(() => {
            if (self.isAccountAuth) {
              self.joinAccountRoom(2);
            }
          });
                    self.triggerEvent('RoomEvent', {
                        tag: 'LinkOn',
                        code: 0,
            detail: '连麦成功完成',
          });
                },
                fail: function (e) {
          console.error('连麦失败: ', e);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: 0,
            detail: '连麦失败',
          });
        },
      });
        },

        playMixedUrl() {
      console.log('==> playMixedUrl');
      let self = _this;
      let players = [
        {
                debug: false,
                mute: false,
                url: self.data.audience.mixUrl,
                mode: 'live',
                maxCache: 3,
                minCache: 1,
                loading: false,
          objectFit: 'fillCrop',
          userName: self.data.audience.pusherName,
        },
      ];
            return new Promise((resolve) => {
        self.setData(
          {
            visualPlayers: players,
          },
          function() {
                    // self.data.playerContext = wx.createLivePlayerContext('player', self);
                    // self.data.playerContext.play();
            resolve();
          },
        );
      });
        },

        playAccelerateUrl() {
      console.info('playAccelerateUrl() called');
      let self = _this;
      let players = [
        {
                debug: false,
                mute: false,
                url: self.data.audience.accelerateUrl,
                mode: 'RTC',
                maxCache: 0.3,
                minCache: 0.1,
                loading: false,
                objectFit: 'fillCrop',
          userName: self.data.audience.pusherName,
        },
      ];
            return new Promise((resolve) => {
        self.setData(
          {
            visualPlayers: players,
          },
          function() {
                    // self.data.playerContext = wx.createLivePlayerContext('player', self);
            resolve();
          },
        );
            });
        },

        stopPlayUrl() {
      let self = _this;
            // self.data.playerContext && self.data.playerContext.stop();
            return new Promise((resolve) => {
        self.setData(
          {
                    visualPlayers: [],
          },
          function() {
            resolve();
          },
        );
            });
        },

        getPushUrl() {
      console.info('getPushUrl() called');
      let self = _this;
            return new Promise(function (resolve, reject) {
                liveroom.getPushURL({
                    success: function (ret) {
                        console.log('getPushURL() 成功，', ret);
            resolve(ret.pushURL);
                    },
                    fail: function (e) {
                        console.log('getPushUrl() 获取推流地址失败: ', e);
            reject(e);
          },
        });
                });
        },
        startLinkPush(url) {
      console.info('startLinkPush() called');
      let self = _this;
            return new Promise(function (resolve, reject) {
                self.data.linkPusherInfo.url = url;
                self.data.members.splice(0, 1);

                console.log('设置推流模式为:RTC');
        self.setData(
          {
                    members: self.data.members,
                    linkPusherInfo: self.data.linkPusherInfo,
            mode: 'RTC',
          },
          function() {
                    self.data.pusherContext = wx.createLivePusherContext('audience_pusher');
                    console.log('startLinkPush.创建 pusherContext：', self.data.pusherContext);
                    self.data.pusherContext.start();
            resolve();
          },
        );
                });
        },
        link() {
      let self = this;
            //停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher
            Promise.resolve()
                .then(self.stopPlayer)
                .then(self.playAccelerateUrl)
                .then(self.getPushUrl)
                .then(self.startLinkPush)
                .then(function () {
                    return new Promise(function (resolve, reject) {
            console.log('----> link() self.data: ', self.data);
            resolve();
          });
                })
                .catch(function (e) {
          console.log(
            '过程出错： 停止mix流播放 --> 播放 accelerate流 --> 获取推流连接开始推流 --> onLinkPush 成功后 jionPusher: ',
            e,
          );
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1,
            detail: '连麦过程发生错误',
          });
                    });
        },
        requestJionPusher() {
      console.log('requestJionPusher() called');
      let self = _this;
            if (self.data.requestLinking){
                wx.showToast({
                    title: '等待大主播接受连麦',
                    duration: 1000,
        });
                return;
            }
      console.info('用户请求连麦');
            self.data.requestLinking = true;
            liveroom.requestJoinPusher({
                data: {
          timeout: 10000,
                },
                success: function (ret) {
                    self.data.requestLinking = false;
          console.log('请求连麦成功: ', ret);
                    self.link();
                },
                fail: function (e) {
          console.log('请求连麦失败: ', e);
                    self.data.requestLinking = false;
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -9004,
            detail: '请求连麦失败',
          });
        },
            });
        },

        onLinkError(e) {
      console.error('onLinkError() called: ', e);
            self.triggerEvent('RoomEvent', {
                tag: 'error',
                code: -2,
        detail: '播放错误',
      });
        },
        kickoutSubPusher(e) {
            console.log('kickoutSubPusher() called');
      let self = _this;
      console.log('==> kickoutSubPusher: ', e);
      let userID = e.currentTarget.dataset.userid;
            liveroom.kickoutSubPusher({
                data: { userID: userID },
                success: (ret) => {
          console.log('--> 踢人成功： ', ret);
          let members = self.data.members;
          let index = members.map((m) => m.userID).indexOf(userID);
                    if (index != -1) {
                        // members[index].context && members[index].context.stop();
            members.splice(index, 1);
            members.push({});
                    }
                    self.setData({
            members: members,
          });
          console.log('data.members: ', self.data.members);
                },
                fail: (e) => {
          console.log('---> 踢人失败： ', e);
        },
      });
            //todo
        },
        quitLink() {
      console.log('quitLink() called');
      let self = this;
            liveroom.quitPusher({
                success: (ret) => {
          console.log('quitPusher 成功：', ret);
                    self.resetToAudience();
                },
                fail: (e) => {
                    console.error('quitPusher Error: ', e);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1,
            detail: '退出连麦"quitPusher"返回错误',
          });
        },
      });
        },
        resetToAudience() {
            console.log('resetToAudience() called');
      let self = _this;
            Promise.resolve()
        .then(() => {
          // 停止推流
          console.log('停止推流');
                    return new Promise((resolve) => {
            console.log('停止推流');
                        self.data.pusherContext && self.data.pusherContext.stop();
                        self.data.linkPusherInfo.url = null;
            self.setData(
              {
                            pusherContext: null,
                linkPusherInfo: self.data.linkPusherInfo,
              },
              () => resolve(),
            );
          });
                    })
        .then(() => {
          // 清理member players
          console.log('清理 member players');
                    return new Promise((resolve) => {
            let pushers = self.data.members;
            pushers &&
              pushers.forEach((p) => {
                p.context && p.context.stop();
              });
            pushers = self.data.template == '1v1' ? [{}] : [{}, {}, {}];
                        self.setData({ members: pushers }, () => resolve());
                    });
                })
                .then(self.stopPlayUrl) // 停止播放 acelerate 流
                .then(self.playMixedUrl) //播放mixed 流
                .then(()=>{
          if (self.isAccountAuth) {
            self.leaveAccountRoom(2);
          }
                    return new Promise((resolve)=>{
                        self.triggerEvent('RoomEvent', {
                            tag: 'LinkOut',
                            code: 0,
              detail: '连麦断开',
            });
                        resolve();
          });
                })
                .catch((e) => {
                    console.error('resetToAudience 流程出现错误：', e);
        });
        },
        onLinkPusherQuit(ret) {
      console.log('onLinkPusherQuit() called ', ret);
      let self = _this;
      let pushers = ret.pushers;
            if (!pushers) return;
      let userIndex = pushers
        .map((p) => {
          return p.userID;
        })
        .indexOf(self.data.userID);
      if (userIndex != -1) {
        // 自己退出link

                self.resetToAudience();
      } else {
        // 别人退出link
                self.onPusherQuit(ret);
            }
        },

        onLinkKickOut(ret) {
            console.log('onLinkKickOut() called');
      let self = _this;
      console.log('%c onLinkKickOut: ', 'color: red;', ret);
            self.quitLink();
        },

        onPushEvent(code) {
      let self = this;
            switch (code) {
                case -1301: {
                    console.log('打开摄像头失败: ', code);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1301,
            detail: '打开摄像头失败',
          });
                    break;
        }
                case -1302: {
                    console.log('打开麦克风失败: ', code);
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1302,
            detail: '打开麦克风失败',
          });
                    break;
        }
                case -1307: {
                    console.error('推流连接断开: ', code);
                    // 推流连接断开就做退房操作
                    self.exit();
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1307,
            detail: '推流连接断开',
          });
                    break;
        }
                case -1305 : {
                    console.log('不支持的视频分辨率');
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1305,
            detail: '不支持的视频分辨率',
          });
                    break;
                }
                case -1306 : {
                    console.log('不支持的音频采样率');
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: -1306,
            detail: '不支持的音频采样率',
          });
                    break;
                }
                default: {
                    console.log('推流事件：', code);
                    break;
                }
            }
        },
        onLinkPush(ret) {
      let self = this;
            console.log('onLinkPush推流情况：', ret.detail.code);
            switch (ret.detail.code) {
                case 1002: {
                    console.log('onLinkPush推流成功：', ret.detail.code);
                    self.linkJionPusher();
                    break;
        }
                case 5000: {
                    console.log('收到5000: ', ret.detail.code);
                    // 收到5000就退房
                    self.exit();
                    self.data.exit = 5000;
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: 5000,
            detail: '收到5000就退房',
          });
                    break;
        }
                default: {
                    self.onPushEvent(ret.detail.code);
                    break;
                }
            }
        },
        onMainPush(ret) {
      let self = this;
      console.log('>> onMainPush() called: ', ret);
            console.log('推流情况：', ret.detail.code);
            switch (ret.detail.code) {
                case 1005: {
          console.log('推流动态分辨率改变： ', ret);
                    break;
                }
                case 1002: {
                    console.log('推流成功：', ret.detail.code);
                    if (!self.data.isInRoom) {
                        self.setData({ isInRoom: 1 });
                        //4.推流成功，请求CGI:create_room，获取roomID、roomSig
                        self.create();
                    }
                    break;
        }

                case 5000: {
                    console.log('收到5000: ', ret.detail.code);
                    // 收到5000就退房
                    self.exit();
                    self.data.exit = 5000;
                    self.triggerEvent('RoomEvent', {
                        tag: 'error',
                        code: 5000,
            detail: '收到5000就退房',
          });
                    break;
        }
                default: {
                    self.onPushEvent(ret.detail.code);
                    break;
                }
            }
        },
        onMainError(e) {
      let self = this;
      console.error('onMainError called: ', e);
            self.triggerEvent('RoomEvent', {
                tag: 'error',
                code: -1,
        detail: (e.detail && e.detail.errMsg) || '推流错误',
      });
        },

        onMainPlayState(e) {
      console.log('===> onMainPlayState: ', e);
        },

        onMainPlayError(e) {
      console.log('===> onMainPlayError: ', e);
        },

        onRoomClose(e) {
      console.log('onRoomClose: e=', e);
      _this && _this.triggerEvent('RoomEvent', { tag: 'roomClosed', code: -9006, detail: '房间已经解散了' });
        },

    wrapTextLine(text) {
      let width = 15;
      let textArray = text.split('');
      let lines = [];
      let line = '';
      for (let i = 0; i < textArray.length; i++) {
        let temp = line + textArray[i];
        if (this.ctx.measureText(temp).width + width >= 276 && i > 0) {
          lines.push(line);
          line = textArray[i];
        } else {
          line = temp;
        }
        if (i == textArray.length - 1) {
          lines.push(line);
        }
      }
      return lines;
    },

    updateAudienceComment() {
      const self = this;
      const comment = this.data.comment;
      this.ctx.clearActions();
      this.ctx.setTextBaseline('top');
      this.ctx.font = 'normal bold 14px PingFangSC';
      let y = 126;
      comment.forEach((element) => {
        self.ctx.setFillStyle('#fff');
        let text = element.name ? `${element.name}: ${element.content}` : element.content;
        let lines = self.wrapTextLine(text);
        let namePrinted = true;
        lines.forEach(function(line, index) {
          if (index === 0) {
            y += -18 * (lines.length - 1);
            if (lines[0].indexOf(':') > -1) {
              let o = lines[0].indexOf(':');
              namePrinted = true;
              self.ctx.setFillStyle('#00ECFE');
              self.ctx.fillText(lines[0].slice(0, o + 1), 0, y);
              self.ctx.setFillStyle('#FFFFFF');
              self.ctx.fillText(lines[0].slice(o + 1), self.ctx.measureText(lines[0].slice(0, o + 1)).width, y);
            } else {
              namePrinted = false;
              self.ctx.setFillStyle('#00ECFE');
              self.ctx.fillText(lines[0], 0, y);
            }
          } else {
            y -= -18;
            if (namePrinted) {
              self.ctx.setFillStyle('#FFFFFF');
              self.ctx.fillText(line, 0, y);
            } else {
              let r = line.indexOf(':');
              if (r > -1) {
                self.ctx.setFillStyle('#00ECFE');
                self.ctx.fillText(line.slice(0, r + 1), 0, y);
                self.ctx.setFillStyle('#FFFFFF');
                self.ctx.fillText(line.slice(r + 1), 0, y);
                namePrinted = true;
              } else {
                self.ctx.setFillStyle('#00ECFE');
                self.ctx.fillText(line, 0, y);
                namePrinted = false;
              }
            }
          }
        });
        y += -18 * lines.length;
      });
      this.ctx.draw(false);
    },
    updateCasterComment() {
      const comment = this.data.comment;
      this.ctx.font = 'normal bold 14px PingFangSC';
      comment.forEach((element) => {
        this.ctx.setFillStyle('#fff');
        let text = element.name ? `${element.name}: ${element.content}` : element.content;
        let lines = this.wrapTextLine(text);
        let namePrinted = true;
        element.lines = [];
        element.lineCount = lines.length;
        lines.forEach((line, index) => {
          if (index === 0) {
            if (line.indexOf(':') > -1) {
              let o = line.indexOf(':');
              let text = line.slice(0, o + 1);
              element.lines.push({
                text,
                color: '#00ECFE',
                inline: true,
                width: this.ctx.measureText(text).width,
              });
              text = line.slice(o + 1);
              element.lines.push({
                text,
                inline: true,
                width: this.ctx.measureText(text).width,
              });
              namePrinted = true;
            } else {
              element.lines.push({
                text: line,
                color: '#00ECFE',
              });
              namePrinted = false;
            }
          } else {
            if (namePrinted) {
              element.lines.push({
                text: line,
              });
            } else {
              let r = line.indexOf(':');
              if (r > -1) {
                let text = line.slice(0, r + 1);
                element.lines.push({
                  text,
                  color: '#00ECFE',
                  inline: true,
                });
                text = line.slice(r + 1);
                element.lines.push({
                  text,
                  inline: true,
                });
                namePrinted = true;
              } else {
                element.lines.push({
                  text: line,
                  color: '#00ECFE',
                });
                namePrinted = false;
              }
            }
          }
        });
      });
      this.setData({
        casterComment: JSON.parse(JSON.stringify(comment)).reverse(),
      });
    },
        onRecvRoomTextMsg(ret) {
      let self = _this;
      console.log('onRecvRoomTextMsg called, ret: ', ret);
      self.data.comment.unshift({
        content: ret.message,
        name: ret.userName,
        time: ret.time,
      });
      self.setData(
        {
          comment: self.data.comment.slice(0, 8),
        },
        function() {
          if (self.data.isCaster) {
            self.updateCasterComment();
          } else {
            self.updateAudienceComment();
          }
        },
      );
            self.triggerEvent('RoomEvent', {
                tag: 'recvTextMsg',
                code: 0,
        detail: ret,
      });
        },
    showTip() {
      if (!this.tipInterval) {
        this.showTipAnimation();
        this.tipInterval = setInterval(() => {
          this.showTipAnimation();
        }, 4000);
      }
    },
    showTipAnimation() {
      if (this.tips && this.tips.length > 0) {
        this.animation.left('-750rpx').translateX(device.windowWidth).step();
        this.setData({
          tip: this.tips.pop(),
          tipAnimation: this.animation.export(),
        }, () => {
          setTimeout(() => {
            this.animation.translateX(-device.windowWidth).step();
            this.setData({
              tipAnimation: this.animation.export(),
            });
          }, 2800);
        });
      }
    },
        onSketchpadData(ret) {
      let self = _this;
      console.log('onSketchpadData called, ret: ', ret);
            self.triggerEvent('RoomEvent', {
                tag: 'sketchpadData',
                code: 0,
        detail: ret,
      });
        },

        onPushersChange() {
      let self = _this;
          if (self && self.data && !self.data.isCaster) {
            //观众端
            liveroom.getPushers({
              success: function (res) {
            let pushers = res.data.pushers;
                if (pushers && pushers.length > 1) {
                  //连麦状态下，因为后台混流，会引入约2s的时延，所以这里把缓冲区设为1-3s，以保持和非连麦状态下的时延基本一致
              console.log('处于连麦状态，改变播放缓冲区时长为1-3s');
                  if (self.data.visualPlayers && self.data.visualPlayers.length > 0) {
                    var player = self.data.visualPlayers[0];
                    player.maxCache = 3;
                    self.setData({
                  visualPlayers: self.data.visualPlayers,
                });
                  }
                } else {
              console.log('处于非连麦状态，改变播放缓冲区时长为1-5s');
                  if (self.data.visualPlayers && self.data.visualPlayers.length > 0) {
                    var player = self.data.visualPlayers[0];
                    player.maxCache = 5;
                    self.setData({
                  visualPlayers: self.data.visualPlayers,
                });
                  }
                }
              },
          fail: function(res) {},
        });
          }
        },
    _setRooomPassWord(roomid, password, connect_status) {
      // 设置房间密码以及连麦权限
      let data = {
              op: 'createRoomPwd',
              roomid,
              password,
              connect_status,
      };
      const { pureAudio } = this.data;
      const { userID: userid = '' } = liveroom.getAccountInfo();

      if(!pureAudio){  //纯视频
        data = Object.assign(data, { userid });
      }

      app.util.request({
        url: 'entry/wxapp/index',
        data,
            module: 'cm_trtc',
        success: (res) => {
              console.log('设置房间密码&&连麦权限成功', res);
            },
        fail: (res) => {
              console.error('设置房间密码&&连麦权限失败', res);
            },
          });
        },
        changeVoice(){
          this.setData({
            isShowVoice: !this.data.isShowVoice,
      });
    },
    },

    attached: function () {
    console.log('ready() called');
        // 保持屏幕常亮
        wx.setKeepScreenOn({
      keepScreenOn: true,
    });

    let self = this;
        _this = this;
    this.tips = [];
    this.tipInterval = null;
    let { userID, userName } = liveroom.getAccountInfo();
        self.data.isCaster = self.data.role == 'presenter';

        self.setData({
            isCaster: self.data.isCaster,
            userID: userID,
            userName: userName,
            unload: 0,
            members: self.data.template == '1v1' ? [{}] : [{},{},{}],
            audienceCount: 0,
      beauty: self.data.pureAudio ? 0 : 5,
        });
    console.log('======data: ', self.data);
    this.checkDebug();
    },

    detached: function () {
    console.log('detached() called');
    wx.setKeepScreenOn({
      keepScreenOn: false,
    });
    let self = this;
        _this = null;
        self.stop();
        if (memberInterval) {
          clearInterval(memberInterval);
        }
    if (this.tipInterval) {
      clearInterval(this.tipInterval);
    }
    },
    ready() {
    let self = _this;
    this.getUserInfo1();
       this.setData({
        isAdmin: app.globalData.isAdmin||'',
        connectStatus: app.globalData.connectStatus||0,
    });
      console.log('==================live-room.js isAdmin',this.data.isAdmin);
      console.log('==================live-room.js connectStatus',this.data.connectStatus);
    self.animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    });
    },
});
